from distutils.log import Log

# from api_test.api.base_api import BaseApi

import requests
import json
from datetime import datetime, timedelta, timezone


# 向钉钉群输出信息
# def msg(text):
#     token = "3c02aae714e8a469ac1b1d3786f818220908202c14dfeb272ce04c9b6325d0db"
#     headers = {'Content-Type': 'application/json;charset=utf-8'}  # 请求头
#     api_url = f"https://oapi.dingtalk.com/robot/send?access_token={token}"
#     json_text = {
#         "msgtype": "text",  # 信息格式
#         "text": {
#             "content": 'python' + text
#         }
#     }
#     # 发送并打印信息
#     print(requests.post(api_url, json.dumps(json_text), headers=headers).content)
#

# # 测试函数
# def onTick():
#     arr = ['BTC', 'ETH', 'XRP', 'BCH', 'LTC']  # 主流数字货币
#     # 获取东八区时间
#     bj_dt = str(datetime.now().astimezone(timezone(timedelta(hours=8))))
#     bj_dt = bj_dt.split('.')[0]  # 处理时间
#     text = f'{bj_dt}\n'  # 定义信息内容
#     for i in arr:  # 循环主流数字货币数组
#         exchange.IO("currency", f"{i}_USDT")  # 切换交易对
#         ticker = exchange.GetTicker().Last  # 获取最新价格
#         if i == 'LTC':
#             full = ' ：'
#         else:
#             full = '：'
#         text = text + f"{i}/USDT{full}${ticker}\n"  # 处理信息内容
#     msg(text)  # 调用msg函数，输出信息
#
#
# # 策略入口
# def main():
#     while True:  # 进入无线循环
#         onTick()  # 执行onTick函数
#         Sleep(1000 * 60)  # 休眠一分钟
# msg("测试报告")


# def dingtalk(msg, message):
#     token = "3c02aae714e8a469ac1b1d3786f818220908202c14dfeb272ce04c9b6325d0db"
#     headers = {'Content-Type': 'application/json; charset=utf-8'}
#     data = {'msgtype': 'text', 'text': {'title': msg, "content": message, 'messageUrl': 'http://请求IP+端口号'}, 'at': {'atMobiles': ['群消息@的用户1', '群消息@的用户2'], 'isAtAll': False}}
#     webhook_url = f"https://oapi.dingtalk.com/robot/send?access_token={token}"
#     post_data = json.dumps(data)
#     response = requests.post(webhook_url, headers=headers, data=post_data)
#     return response.text
#
#
# # 复制出来的webhook
# message = "python" + "这是测试数据"
# print(dingtalk("出库数据核对", message))

class DingHook(object):
    def __init__(self):
        token = "619fbb960461fed4c65d48ad137752ec3e1d7124205334cb1687e5041ccc1dc9"
        self.url = f"https://oapi.dingtalk.com/robot/send?access_token={token}"

    # 钉钉发送markdown方法
    def markdown(self, project, text, text1):
        data = {
            "msgtype": "markdown",

            "markdown": {
                "title": "小白",

                "text": f'### **{project}**\n' +

                        f">#### {text}\n\n" +

                        "> ![screenshot](file:///D:/cqz/jmeter/ant-jmeter-test/report/html/TestReport202112101109.html)\n" +

                        f"> ##### {text1} \n" 

                "> ###### 具体可查看邮件: [链接](https://gitee.com/cqz5858/projects) \n"

            },

            "at": {
                "atMobiles": [

                    "1860176xxxx",

                    ""

                ],

                "isAtAll": False

            }

        }

        data = json.dumps(data).encode(encoding='UTF8')

        headers = {"Content-Type": "application/json"}

        response = requests.post(self.url, data=data, headers=headers)

        # 调用钉钉返回结果转json格式

        res_code = json.loads(response.text)

        # print(res_code['errcode'])

        if res_code['errcode'] == 0:

            print('钉钉消息推送成功！')

            # Logger().write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+'  ' +"钉钉消息推送成功\n")

        else:

            print(f"钉钉消息推送失败!: {res_code}")

            # Logger().write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  +"钉钉消息推送失败\n")


dh = DingHook()
dh.markdown('企探1.2接口测试', '企业结果页', '测试通过')
